package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.lang.UUID;
import com.atguigu.spzx.manager.properties.MinioProperties;
import com.atguigu.spzx.manager.service.FileUploadService;
import io.minio.*;
import lombok.SneakyThrows;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author yaya
 * @Create 2024/6/24 19:06
 * Description:
 */
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    MinioProperties minioProperties;

    @SneakyThrows
    @Override
    public String fileUpload(MultipartFile multipartFile) {

        MinioClient minioClient = MinioClient.builder()
                .endpoint(minioProperties.getEndpoint())
                .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                .build();

        // 判断桶是否存在，不存在则创建桶
        BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder()
                .bucket(minioProperties.getBucketName()).build();
        if (!minioClient.bucketExists(bucketExistsArgs)) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
        }

        // 上传信息的格式: 日期 + UUID +原文件名
        String nowDay = new DateTime().toString(DateTimeFormat.forPattern("yyyy/MM/dd"));
        String uploadName = nowDay + UUID.randomUUID().toString().replace("-", "") + multipartFile.getOriginalFilename();
        // 保存文件
        minioClient.putObject(PutObjectArgs.builder()
                .stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                .contentType(multipartFile.getContentType())
                .object(uploadName)
                .bucket(minioProperties.getBucketName())
                .build());

        // 拼接字符串， 可以得到直接访问的url地址给前端
        String url = String.join("/", minioProperties.getEndpoint(), minioProperties.getBucketName(), uploadName);
        return url;
    }
}
